# coding=utf-8
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor
import threading
import time
import sys
import datetime


class Echo(Protocol):
    def __init(self):
        self.connected = False

    def connectionMade(self):
        self.connected = True

    def connectionLost(self, reason):
        self.connected = False

    def dataReceived(self, data):
        print(data.decode("utf-8"))


class EchoClientFactory(ClientFactory):
    def __init__(self):
        self.protocol = None

    def startedConnecting(self, connector):
        print("start to connect....")

    def buildProtocol(self, addr):
        print("connected....")
        self.protocol = Echo()
        return self.protocol

    def clientConnectionLost(self, connector, reason):
        print("lost connection reason:", reason)

    def clientConnectionFailed(self, connector, reason):
        print("connection is failed, reason:", reason)


bStop = False


def routine(factory):
    while not bStop:
        if factory.protocol and factory.protocol.connected:
            str = "hello, I'am %s %s" % (sys.argv[0], datetime.datetime.now())
            factory.protocol.transport.write(str.encode("utf-8"))
            print(str)

        time.sleep(5)
        print("bStop=", bStop)


host = "127.0.0.1"
port = 8007
factory = EchoClientFactory()
reactor.connectTCP(host, port, factory)
threading.Thread(target=routine, args=(factory,)).start()
reactor.run()
bStop = True
print("bStop=", bStop)
